package lenovo.asd.xml;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;


public class XMLContentHandler extends DefaultHandler {
	
	private static final String FUNC_SEQ_TAG="XMLContentHandler";
	
	private List<Task> tasks;
	private Task task;
	private String preTag;
	
	public List<Task> getTasks() {
		Log.e(FUNC_SEQ_TAG, "enter getTasks()");
		return tasks;
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		Log.e(FUNC_SEQ_TAG, "enter endElement()");
		
		if ("task".equals(localName) && task!=null) {
			tasks.add(task);
			task = null;
		}
		preTag = null;
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		Log.e(FUNC_SEQ_TAG, "enter startDocument()");
		tasks = new ArrayList<Task>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		Log.e(FUNC_SEQ_TAG, "enter startElement()");
		
		if ("task".equals(localName)) {
			task = new Task();
			task.setId(new Integer(attributes.getValue("", "id")));
		}
		preTag = localName;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		Log.e(FUNC_SEQ_TAG, "enter characters()");
		
		if (task != null) {
			String data = new String (ch, start, length);
			// me: change element name with config.xml
			if ("name".equals(preTag)) {
				task.setName(data);
			} else if ("age".equals(preTag)) {
				task.setAge(new Short(data));
			}
		}

	}
	
	
}
